package main

import (
	"flag"
	"fmt"
	"io"
	"net"
	"os"
)

type Client struct {
	ServerIp   string
	ServerPort int
	Name       string
	conn       net.Conn
	flag       int
}

var serverIp string
var serverPort int

func (client *Client) chooseMenu() bool {
	var flag int
	fmt.Println("1、公共聊天室")
	fmt.Println("2、私信")
	fmt.Println("3、更改用户名")
	fmt.Println("0、退出")
	fmt.Scanln(&flag)
	if flag >= 0 && flag <= 3 {
		client.flag = flag
		return true
	} else {
		fmt.Println(">>>>>请输入合法的菜单选项<<<<<")
		return false
	}
}

func CreateClient(serverIp string, serverPort int) *Client {
	client := &Client{
		ServerIp:   serverIp,
		ServerPort: serverPort,
		flag:       999,
	}

	conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", serverIp, serverPort))
	if err != nil {
		fmt.Println("net.Dial error:", err)
		return nil
	}

	client.conn = conn
	return client
}

func (client *Client) run() {
	for client.flag != 0 {
		//死循环直至输入正确的选项
		for client.chooseMenu() != true {
		}

		switch client.flag {
		case 1:
			//聊天室
			client.PublicChat()
			break
		case 2:
			//私信
			client.PrivateChat()
			break
		case 3:
			//更新用户名
			client.UpdateName()
			break
		}

	}
}

func (client *Client) SelectUsers() {
	snedMsg := "who\n"
	_, err := client.conn.Write([]byte(snedMsg))
	if err != nil {
		fmt.Println("client.conn.Write error:", err)
		return
	}

}

func (client *Client) PrivateChat() {
	var remoteName string
	for remoteName != "exit" {
		client.SelectUsers()
		fmt.Println(">>>>>请输入聊天对象用户名，exit退出")
		fmt.Scanln(&remoteName)
		var content string
		for content != "exit" {
			content = ""
			fmt.Println(">>>>>请输入消息内容，exit退出")
			fmt.Scanln(&content)
			if len(content) != 0 {
				sendMsg := fmt.Sprintf("to|%s|%s\n\n", remoteName, content)
				_, err := client.conn.Write([]byte(sendMsg))
				if err != nil {
					fmt.Println("client.conn.Write error:", err)
					break
				}
			}
		}
	}

}

func (client *Client) PublicChat() {
	//请输入
	fmt.Println(">>>>>已进入聊天室，发送任意消息，或exit退出")

	var content string
	fmt.Scanln(&content)

	for content != "exit" {
		if len(content) != 0 {
			sendMsg := content + "\n"
			_, err := client.conn.Write([]byte(sendMsg))
			if err != nil {
				fmt.Println("conn.Write error:", err)
			}
		}

		content = ""
		fmt.Scanln(&content)
	}
}

func (client *Client) UpdateName() bool {
	fmt.Println(">>>>>请输入用户名:")
	fmt.Scanln(&client.Name)

	sendMsg := fmt.Sprintf("rename|%s", client.Name)

	_, err := client.conn.Write([]byte(sendMsg))
	if err != nil {
		fmt.Println("conn.Write error:", err)
		return false
	}

	return true
}

func (client *Client) ProcessResponse() {
	//有消息就拷贝到标准输出上，永久阻塞监听
	io.Copy(os.Stdout, client.conn)
}

func init() {
	flag.StringVar(&serverIp, "ip", "127.0.0.1", "设置服务器IP地址（默认127.0.0.1）")
	flag.IntVar(&serverPort, "port", 8888, "设置服务器端口（默认8888）")
}

func main() {
	client := CreateClient(serverIp, serverPort)
	if client == nil {
		fmt.Println(">>>>>连接服务器失败<<<<<")
		return
	}

	go client.ProcessResponse()

	fmt.Println(">>>>>连接服务器成功<<<<<")

	client.run()
	select {}
}
